package com.lujieni.test.testidle;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.net.InetSocketAddress;

public class HelloClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        new Bootstrap()
                .group(eventExecutors)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    // 在连接建立后被调用,仅仅是加了处理器而已
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder()); // 将ByteBuf转为String
                        ch.pipeline().addLast(new IdleStateHandler(0, 3, 0));
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                eventExecutors.shutdownGracefully();
                                super.channelInactive(ctx);
                            }

                            @Override
                            public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                                IdleStateEvent event = (IdleStateEvent) evt;
                                if (event.state() == IdleState.WRITER_IDLE) {
                                    ctx.writeAndFlush("ping ping");
                                }
                                super.userEventTriggered(ctx, evt);
                            }
                        });
                    }
                })
                .connect(new InetSocketAddress("localhost", 8081))
                .sync() // 阻塞方法直到连接建立
                .channel() // 代表连接对象
                .writeAndFlush("hello world"); // 向服务器发送数据


    }
}
